<template>
  <layoutPage class="details">
    <template #search>
      <div class="top">
        <el-descriptions class="basic-info" :column="4">
          <template #title>
            <div class="title">
              <el-tag :type="attendStatus.colorType" size="small" effect="dark">
                {{ attendStatus.label }}
              </el-tag>
              <span>【ID:{{ basicInfo.id }}】</span>
              <span>{{ basicInfo.meetingTopic }}</span>
            </div>
          </template>
          <el-descriptions-item label="会议开始时间：">
            {{ updateTime(basicInfo.startTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="预估会议时长：">
            {{ formatMinutes(basicInfo.estimatedDuration) }}
          </el-descriptions-item>
          <el-descriptions-item label="会议地点：">
            <el-tooltip
              v-if="basicInfo.description.length > 10"
              effect="dark"
              :content="basicInfo.location"
              placement="top"
            >
              <span>{{ basicInfo.location.slice(0, 10) }}...</span>
            </el-tooltip>
            <span v-else>{{ basicInfo.location }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="组织人：">
            {{ basicInfo.creatorName }}
          </el-descriptions-item>
          <el-descriptions-item label="会议类型：">
            {{
              _discStore.getDictLabelForValue(
                'meeting_type',
                basicInfo.meetingType
              )
            }}
          </el-descriptions-item>
          <el-descriptions-item label="结论状态：">
            <el-tag
              :type="conclusionStatus(basicInfo.conclusionStatus).colorType"
            >
              {{ conclusionStatus(basicInfo.conclusionStatus).label }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="basicInfo.participationStatus"
            label="我的参会反馈："
          >
            <template
              v-if="
                basicInfo.participationStatus === '3' ||
                basicInfo.participationStatus === '2'
              "
            >
              <el-tag
                :type="
                  participantStatus(basicInfo.participationStatus).colorType
                "
              >
                {{ participantStatus(basicInfo.participationStatus).label }}
              </el-tag>
            </template>
            <template v-else>
              <el-button size="small" type="success" @click="handleAccept">
                接受
              </el-button>
              <el-button size="small" type="danger" @click="handleReject">
                拒绝
              </el-button>
            </template>
          </el-descriptions-item>
          <el-descriptions-item label="会议描述：" min-width="80">
            <el-tooltip
              v-if="basicInfo.description.length > 10"
              effect="dark"
              :content="basicInfo.description"
              placement="top"
            >
              <span>{{ basicInfo.description.slice(0, 10) }}...</span>
            </el-tooltip>
            <span v-else>{{ basicInfo.description }}</span>
          </el-descriptions-item>
        </el-descriptions>
        <div class="buttonList">
          <el-button v-if="isButtonShow" type="primary" @click="handleFill">
            会议结论填报
          </el-button>
          <el-button v-if="!isButtonShow" type="success" @click="handleEdit">
            编辑会议信息
          </el-button>
          <el-button v-if="!isButtonShow" type="danger" @click="handleDelete">
            删除
          </el-button>
        </div>
      </div>
    </template>
    <div class="content">
      <div class="panel">
        <div class="display-title">参与人</div>
        <el-table :data="basicInfo.participants" border>
          <el-table-column type="index" label="序号" min-width="50" />
          <el-table-column
            prop="participantName"
            label="参会人"
            min-width="120"
          />
          <el-table-column prop="status" label="是否参会反馈" min-width="120">
            <template #default="{ row }">
              <el-text :type="participantStatus(row.status).colorType">
                {{ participantStatus(row.status).label }}
              </el-text>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="panel">
        <div class="display-title">关联信息</div>
        <el-table :data="basicInfo.associations" border>
          <el-table-column type="index" label="序号" min-width="50" />
          <el-table-column prop="associationType" label="类型" min-width="120">
            <template #default="{ row }">
              <span>
                {{
                  _discStore.getDictLabelForValue(
                    'meeting_association_type',
                    row.associationType
                  )
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="associationContent"
            label="内容"
            min-width="120"
          >
            <template #default="{ row }">
              <el-link
                v-if="routeTypes[row.associationType]"
                :underline="false"
                type="primary"
                @click="handleAssociationClick(row)"
              >
                项目名称：{{ row.associationContent }}
              </el-link>
              <span v-else>项目名称：{{ row.associationContent }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="associationId" label="相关ID" min-width="120">
            <template #default="{ row }">
              <span>项目编号：{{ row.associationId }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="panel">
        <div class="display-title">会议结论</div>
        <el-table :data="basicInfo.conclusions" border>
          <el-table-column type="index" label="序号" min-width="50" />
          <el-table-column
            prop="conclusionContent"
            label="内容"
            min-width="120"
          />
          <el-table-column prop="relatedDocuments" label="文档" min-width="120">
            <template #default="{ row }">
              <div v-for="item in row.relatedDocuments" :key="item.id">
                <el-link
                  v-if="item.fileUrl"
                  :underline="false"
                  type="primary"
                  @click="handleClickDoc(item)"
                >
                  文档：{{ item.fileName }}
                </el-link>
                <span v-else>文档：{{ item.fileName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="associationInfos"
            label="关联信息"
            min-width="120"
          >
            <template #default="{ row }">
              <div v-for="item in row.associationInfos" :key="item.id">
                <el-link
                  v-if="routeTypes[item.associationType]"
                  :underline="false"
                  type="primary"
                  @click="handleClickAssociation(item)"
                >
                  项目名称：{{ item.associationContent }}（项目编号：{{
                    item.associationId
                  }}）
                </el-link>
                <span v-else>
                  项目名称：{{ item.associationContent }}（项目编号：{{
                    item.associationId
                  }}）
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </layoutPage>
</template>

<script lang="ts" setup>
  import layoutPage from '@/components/layoutPage.vue'
  import {
    getMeetingsDetails,
    deleteMeetingsInfo,
    getMeetingsUpdateParticipantStatus,
  } from '@/api/project/meeting'
  import { formatMinutes } from '@/utils/index'
  import {
    detailsInfoProps,
    resDetailsProps,
    associationsProps,
    RelatedDocumentsRespVO,
    MeetingAssociationsRespVO,
    resProps,
  } from '../interface'
  import { useDictStore } from '@/store/modules/dict'
  import { useCloseTabNavigate } from '@/utils/useCloseTabNavigate'
  import { useTimeFormat } from '@/utils/useTimeFormat'

  const _discStore = useDictStore()
  const { closeTabNavigate } = useCloseTabNavigate()

  const { updateTime } = useTimeFormat()
  // 路由实例
  const router = useRouter()
  const route = useRoute()
  // 基本信息
  const basicInfo = reactive<Partial<detailsInfoProps>>({})

  // 会议状态属性
  const attendStatus: any = computed(() => {
    const statusInfo = _discStore.getDictForValue(
      'meeting_status',
      basicInfo.status
    ) || {
      colorType: 'info',
      label: '待定',
    }
    return {
      colorType: statusInfo?.colorType || 'info',
      label: statusInfo?.label || '待定',
    }
  })

  // 参会人员状态属性
  const participantStatus: any = computed(() => {
    return (value: string) => {
      const statusInfo = _discStore.getDictForValue(
        'meeting_participation_status',
        value
      ) || {
        colorType: 'info',
        label: '待定',
      }
      return {
        colorType: statusInfo?.colorType || 'info',
        label: statusInfo?.label || '待定',
      }
    }
  })
  // 会议结论状态
  const conclusionStatus: any = computed(() => {
    return (value: string) => {
      const statusInfo = _discStore.getDictForValue(
        'conclusion_status',
        value
      ) || {
        colorType: 'info',
        label: '待下结论',
      }
      return {
        colorType: statusInfo?.colorType || 'info',
        label: statusInfo?.label || '待下结论',
      }
    }
  })
  // status 为1 待开始状态 可显示 编辑和删除按钮，当状态不为1时，可显示结论按钮  同时必须满足 hasOperatePrivilege为true
  const isButtonShow = computed(() => {
    //  会议状态 只要不是1 待开始状态
    return basicInfo.status !== '1' && basicInfo.hasOperatePrivilege
  })
  // 查询明细
  const handleSearchDetails = async (id: string) => {
    try {
      const res: resDetailsProps = await getMeetingsDetails({ id })
      if (res && res.data) {
        Object.assign(basicInfo, res.data)
      } else {
        Object.assign(basicInfo, {})
      }
    } catch (e) {
      console.error('查询会议明细异常', e)
      Object.assign(basicInfo, {})
    }
  }
  // 配置一个路由名称与类型映射关系
  const routeTypes = {
    TOPIC_ADVICE: 'Meeting',
  }
  // 点击跳转对应路由页面
  const handleAssociationClick = (row: associationsProps) => {
    console.log('handleAssociationClick', row)
    router.push({
      name: routeTypes[row.associationType],
      query: { id: row.associationId },
    })
  }

  watch(
    () => ({
      id: route.query?.id,
    }),
    ({ id }: { id: string }) => {
      if (id) {
        handleSearchDetails(id)
      }
    },
    { immediate: true }
  )

  // 会议结论填报
  const handleFill = () => {
    router.push({
      name: 'Meetings_Details_Conclusion',
      query: { id: basicInfo.id },
    })
  }
  // 编辑会议信息
  const handleEdit = () => {
    router.push({
      name: 'Meetings_Kickoff',
      query: { id: basicInfo.id },
    })
  }
  // 删除会议
  const handleDelete = () => {
    ElMessageBox.confirm(`确定删除会议?`, '删除会议', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res: resProps = await deleteMeetingsInfo({ id: route.query.id })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        closeTabNavigate({ name: 'Meetings_List' })
      }
    })
  }

  // 文档下载
  const handleClickDoc = (item: RelatedDocumentsRespVO) => {
    console.log('handleClickDoc', item)
    window.open(item.fileUrl, '_blank')
  }
  // 关联信息跳转
  const handleClickAssociation = (item: MeetingAssociationsRespVO) => {
    router.push({
      name: routeTypes[item.associationType],
      query: { id: item.associationId },
    })
  }

  // 接受
  const handleAccept = () => {
    ElMessageBox.confirm(
      `确定接受${basicInfo.creatorName}的会议邀请?`,
      '接受',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const params = {
        meetingId: route.query.id,
        participantStatus: '2',
      }
      const res: resProps = await getMeetingsUpdateParticipantStatus(params)
      console.log('res', res.code === 0)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '接受成功',
        })
        closeTabNavigate({ name: 'Meetings_List' })
      }
    })
  }

  // 拒绝
  const handleReject = () => {
    ElMessageBox.confirm(
      `确定拒绝${basicInfo.creatorName}的会议邀请?`,
      '拒绝',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      const params = {
        meetingId: route.query.id,
        participantStatus: '3',
      }
      const res: resProps = await getMeetingsUpdateParticipantStatus(params)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '拒绝成功',
        })
        closeTabNavigate({ name: 'Meetings_List' })
      }
    })
  }
</script>

<style lang="scss" scoped>
  .details {
    .top {
      display: flex;
      align-items: center;
      padding-bottom: 20px;

      :deep(.basic-info) {
        flex-grow: 1;
        margin-right: 20px;
        border-right: 1px solid #edeff2;

        .title {
          display: inline-flex;
          align-items: center;
          font-size: 18px;
        }

        .el-descriptions__label {
          margin-right: 0px !important;
        }

        .el-descriptions__title {
          padding-left: 0px;
          border: none;
        }
      }
    }

    .buttonList {
      display: flex;
      flex-direction: column;
      align-items: stretch;

      .el-button {
        flex: 1;
        /* 使按钮在垂直方向上占据相同的空间 */
        width: 100%;

        /* 使按钮在水平方向上占据父容器的宽度 */
        + .el-button {
          margin-top: 10px;
          margin-left: 0px;
        }
      }
    }

    .content {
      .panel {
        margin-bottom: 20px;
      }
    }

    .display-title {
      height: 28px;
      padding-left: 12px;
      margin-bottom: 20px;
      font-size: 14px;
      font-weight: 500;
      line-height: 28px;
      color: #606266;
      background: #f7f8f9;
      border-left: 5px solid #1890ff;
      border-radius: 2px;
    }
  }
</style>
